import java.io.File;
import java.io.FileFilter;
import java.util.Random;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.CountDownLatch;

public class FileCrawler implements Runnable {
	private final BlockingDeque<File>[] fileQueues;
	private final FileFilter fileFilter;
	private final File root;
	private final Random rnd;
	private CountDownLatch cdl;
	private final File POISON_PILL;
	
	public FileCrawler(BlockingDeque<File>[] queues, FileFilter filter, File root, CountDownLatch cdl, File poisonPill) {
		fileQueues = queues;
		fileFilter = filter;
		this.root = root;
		rnd = new Random();
		this.cdl = cdl;
		POISON_PILL = poisonPill; 
	}

	public void run() {
		try {
			crawl(root);
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		}
	}

	private void crawl(File root) throws InterruptedException {
		File[] entries = root.listFiles(fileFilter);
		if (entries != null) {
			for (File entry : entries)
				if (Thread.currentThread().isInterrupted())
					break;
				else if (entry.isDirectory())
					crawl(entry);
				else if (!alreadyIndexed(entry))
					fileQueues[rnd.nextInt(fileQueues.length)].put(entry);
		}
		cdl.countDown();
		cdl.await();
		for (int i = 0; i < fileQueues.length; ++i) {
			fileQueues[i].addLast(POISON_PILL);
		}
	}

	private boolean alreadyIndexed(File entry) {
		return false;
	}
}